package com.note.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.note.common.filter.GatewayOnlyInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 网关安全自动配置
 * 注册拦截器、过滤器等
 */
@Slf4j
@Configuration
@ConditionalOnWebApplication
@ComponentScan("com.note.common.filter")
@ConditionalOnProperty(name = "gateway.access.interceptor.enabled", havingValue = "true", matchIfMissing = true)
public class GatewaySecurityAutoConfiguration implements WebMvcConfigurer {

    @Value("${gateway.access.header:X-Gateway-Access}")
    private String gatewayHeader;

    @Value("${gateway.access.secret:note-gateway-123456}")
    private String gatewaySecret;

    @Value("${gateway.access.enabled:true}")
    private boolean enabled;
    
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 创建网关访问拦截器
     */
    @Bean
    @ConditionalOnMissingBean
    public GatewayOnlyInterceptor gatewayOnlyInterceptor() {
        log.info("创建GatewayOnlyInterceptor拦截器");
        return new GatewayOnlyInterceptor(objectMapper, gatewayHeader, gatewaySecret, enabled);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        GatewayOnlyInterceptor interceptor = gatewayOnlyInterceptor();
        log.info("注册GatewayOnlyInterceptor拦截器");
        registry.addInterceptor(interceptor);
    }
} 